<!DOCTYPE html>
<html>
<head>
	<title>{$site_name}</title>
    <!-- {if(false!==strpos(request()->domain(),'veishou'))} -->
    <link rel="icon" href="/weishou_logo.png" type="image/x-icon"/>
    <!-- {/if} -->
	<meta charset="utf-8">
	<meta name="renderer" content="webkit"/>
    <meta name="force-rendering" content="webkit"/>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"/>
    <script>/*@cc_on window.location.href="{:url('index/index/browser')}" @*/</script>

	<!-- <script src="{:_static()}/cdn/jquery.min.3.2.1.js"></script> -->
	<!-- <script src="{:_static()}/cdn/vue.min.2.5.16.js"></script> -->
	<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
	<script src="https://cdn.staticfile.org/vue/2.5.16/vue.min.js"></script>
	{block name="style"}
	<!-- 这里允许在引入一些样式头部 -->
	{/block}
	<!-- 引入样式 -->
	<!-- <link rel="stylesheet" href="{:_static()}/css/style.css"> -->
	<link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.4.2/theme-chalk/index.css">
	<!-- 引入组件库 -->
	<!-- <script src="{:_static()}/cdn/element-ui.2.4.2.js"></script> -->
	<script src="https://cdn.staticfile.org/element-ui/2.4.2/index.js"></script>
	<!-- <script src="{:_static()}/cdn/tween.16.3.4.js"></script> -->
	<script src="https://cdn.jsdelivr.net/npm/tween.js@16.3.4"></script>
	<link rel="stylesheet" href="{:_static()}/css/style.css">
	<script src="{:_static()}/js/mixins.js"></script>
	<!-- <script src="{:_static()}/cdn/socket.io.2.0.4.js"></script> -->
	<script src="https://cdn.staticfile.org/socket.io/2.0.4/socket.io.slim.js"></script>
	<!-- 引入日历控件 -->
	<link rel="stylesheet" href="{:_static()}/js/jeDate/jedate.css">
	<script src="{:_static()}/js/jeDate/jedate.min.js"></script>
</head>
<body>
<div class="ws-container">
	<div class="ws-left" id="ws-nav" v-show="showLeft" :style="{width:asideWith}" v-cloak>
		<!-- LOGO start -->
		<div class="ws-logo top">
            <!-- {if(false!==strpos(request()->domain(),'veishou'))} -->
            <img src="/weishou_logo.png">
            {$site_name}管理
            <!-- {else} -->
            <img src="/favicon.ico">
            米客云控
            <!-- {/if} -->
		</div>
		<!-- LOGO end -->
		
		<!-- 菜单栏 start -->
		<el-menu :default-active="activeIndex" background-color="#495060" text-color="#fff" style="border-right-width: 0">
		  <template v-for="v of nav" v-if="userNavsIds.indexOf(v.id)>=0">

		  <el-submenu :index="v.id" v-if="v.children">
		    <span slot="title">{{v.title}}</span>
		    <el-menu-item :index="c.id" v-for="c of v.children" style="padding: 0px;" v-if="userNavsIds.indexOf(c.id)>=0">
		      <a class="block w100" style="padding-left: 40px;padding-right: 20px;" :href="c.href" slot="title">{{c.title}}</a>
		    </el-menu-item>
		  </el-submenu>

		  <el-menu-item :index="v.id" style="padding: 0px;" v-else>
		    <a class="block w100 p_x20" :href="v.href" slot="title">{{v.title}}</a>
		  </el-menu-item>

		  </template>
		</el-menu>
		<!-- 菜单栏 end -->
        
        <!-- 客服迷你框 start -->
        <div class="ws-ims-mini no-select" v-show="isMini" @click="isMini=false">
            <span class="ws-ims-headimg">
                <img :src="imagePrefix+customersHeadImage" v-if="customersHeadImage">
                <img :src="defaultHeadImg" v-else>
                <span class="sign" v-show="counts>0">{{counts}}</span>
            </span>
            <span class="main">{$user.name}</span>
        </div>
        <!-- 客服迷你框 end -->

        <!-- 客服完整框 start -->
		<div id="ws-customer" v-show="!isMini">
			<div class="header no-select">
				<span class="title ellipsis">
                    <img :src="imagePrefix+customersHeadImage" style="float:left;margin-top:5px;" v-if="customersHeadImage">
					<img :src="defaultHeadImg" style="float:left;margin-top:5px;" v-else>
					{$user.name}
				</span>
				<span class="close pointer no-select" @click="isMini=true">×</span>
				<p class="sign"></p>
			</div>
			<div class="main">
				<div class="search">
					<el-select
						style="width: 100%;"
						size="mini"
					    v-model="value9"
					    filterable
					    clearable
					    remote
					    reserve-keyword
					    placeholder="请输入关键词"
					    @visible-change="searchChange"
					    :remote-method="remoteMethod"
					    :loading="loading">
					    <el-option
					      v-for="item in options4"
					      :key="item.id"
					      :label="item.name"
					      :value="item.id">
					    </el-option>
					</el-select>
				</div>
				<div class="content no-select">
					<div 
						@dblclick="createSession(item)" 
						class="item ellipsis pointer" 
						v-for="item of customers">
						<div class="left">
							<img :src="imagePrefix+item.head_img" v-if="item.head_img">
							<img :src="defaultHeadImg" v-else>
						</div>
						<div class="right">
							<p class="name ellipsis">
                                <span>{{item.name}}</span>
                                <span v-if="item.is_top" style="color: #FF5E5E;border: solid 1px #FF5E5E;border-radius: 2px; font-size: 12px;padding: 1px;">置顶</span>
							</p>
							
							<div class="foot ellipsis" v-if="item.message" v-html="format10toEmoji(item.message)"></div>
							<div class="foot ellipsis" style="color: #ccc" v-else>暂无消息</div>
                            <span class="sign" v-if="item.notReads>0">
                                <span v-if="item.notReads<100">
                                    {{item.notReads}}
                                <span>
                                <span v-else>99+<span>
                            </span>
						</div>
					</div>
				</div>
			</div>
		</div>
        <!-- 客服完整框 end -->

        <!-- 客服聊天框 start -->
		<el-dialog width="600px" class="ws-ims-session" :visible.sync="value" :show-close="false" >
		    <header slot="title">
		        <span class="title ellipsis">
		            <img :src="imagePrefix+row.head_img" v-if="row.head_img" :style="headImgStyle">
					<img :src="defaultHeadImg" :style="headImgStyle" v-else>
		            与 <span v-text="row.name"></span> 的聊天 
		        </span>
		        <span class="close pointer no-select" @click="close()">×</span>
		    </header>
		    <section id="scrollDIV">
		        <div class="no-logs no-select" v-show="!logs.length">暂无消息</div>
		        <div :class="{item:true,isme:v.relation_id>0?true:false}" v-for="v of logs">
		            <p class="head">
		                <span class="uname" v-if="v.relation_id">客服人员</span>
		                <span class="uname" v-else>{{row.name}}</span>
		                <span class="time">{{dateFormat(parseInt(v.s_time*1000))}}</span>
		            </p>
		            <span class="message">
		                <i :class="['isign',v.relation_id>0?'right':'left']"></i>
		                <span v-html="format10toEmoji(v.message)"></span>
		            </span>
		        </div>
		    </section>
		    <footer>
		    	<div class="toolbar"></div>
		        <textarea class="input-area" v-model="sessionMessage" @focus="sessionFocus=true" @blur="sessionFocus=false"></textarea>
		        <div class="foot">
		            <span class="btn pointer no-select" @click="close()">关闭</span>
		            <span class="btn pointer no-select" @click="send()" style="margin-right:0px;border-radius:2px 0 0 2px;">发送</span>
		            <span class="btn pointer no-select" id="sendKeyType" @click="sendKeyType()" style="margin-left:1px;border-radius:0 2px 2px 0;width: 30px;"><span class="downSign"><span></span>
		        </div>
		        <ul class="send-key" v-show="sendKeyTypeShow">
		            <li @click="changeSendKey('enter')"><span :class="{sign:true,active:sendKey==='enter'}"></span>按Enter键发送消息</li>
		            <li @click="changeSendKey('cEnter')"><span :class="{sign:true,active:sendKey==='cEnter'}"></span>按Ctrl+Enter键发送消息</li>
		        </ul>
		    </footer>
		</el-dialog>
        <!-- 客服聊天框 end -->

	</div>
	<div class="ws-right">
		<!-- 顶部 start -->
		<div class="ws-top top" id="ws-top">
			<el-col :span="3">
			  <el-button @click="showAside" icon="el-icon-menu" type="text" style="font-size: 20px;color: #fff;"></el-button>
			</el-col>

			<el-dropdown placement="bottom" class="f_r">
			  <span class="block" style="color:#fff;cursor: pointer;">
			    {$user.name}
			    <i class="el-icon-arrow-down el-icon--right"></i>
			  </span>
			  <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                    <a href="{:url('admin/setting/user')}">修改密码</a>
                </el-dropdown-item>
			    <el-dropdown-item>
			    	<span @click="onGet('{:url(\'admin/login/logout\')}')">退出</span>
				</el-dropdown-item>
			  </el-dropdown-menu>
			</el-dropdown>
		</div>
		<!-- 顶部 end -->

		<!-- 右侧内容区域 start -->
		<div class="ws-main">
			{block name="main"}右侧内容区域{/block}
		</div>
		<!-- 右侧内容区域 end -->
	</div>

</div>
</body>
</html>
<script type="text/javascript">
const socket = io("{:config('setting.socket_host')}");

socket.on('connect',_=>{
    socket.emit('login',{id:"{$user.id}",login_name:"{$user.login_name}",type:1});
    
});
</script>
<script>
var wsNav=new Vue({
	el:"#ws-nav",
	mixins:[wsMixins],
	data:{
	    aside:200, // 导航宽度
	    nav:{$_navs|stripslashes|raw}, // 菜单
	    activeIndex:{$_navs_id}, // 当前菜单ID
	    userNavsIds:{$_user_navs_ids|raw}, 

	    defaultHeadImg:"{:_static()}/images/ic_user_logo.png",

        customersHeadImage:"{$user['head_img']}",
	    customers:{$customers|raw},
	    imagePrefix:"{:images()}",
	    options4: [],
        value9: '',
        sessionMessage: '',
        loading: false,
        value: false,
        isMini: true,
        counts: {$customer_counts},
        sessionFocus: false,
        row:{},
        logs:{},
        sendKeyTypeShow:false, //按键发送选择菜单
        sendKey:'enter',
        isTopMaxIndex:0,
	},
	computed:{
	    asideWith(){
	      	return this.aside.toString()+'px';
	    },
	    showLeft(){
	    	return this.aside>=200;
	    },
	    headImgStyle(){
	    	return 'border:solid #aaa 1px;border-radius: 50%;font-size: 28px;color: #aaa;width: 30px;height: 30px;';
	    }
	},
	created(){
        this._setIsTopIndex();
        this.initEnter();
        this.enter();
        this.init();
	},
    watch:{
        value(val){
            if(!val){
                this.row={};
                this.logs={};
                this.sessionFocus=false;
                this.sessionMessage='';
            }
        }
    },
	methods: {
        init(){
            socket.on('reconnect_error',err=>{
                // 重连失败 
                this.$notify({
                    title: '提示信息',
                    message: '连接失败，请确保您的Socket服务已经开启，并刷新页面即可!',
                    type: 'warning'
                });
                socket.close();
            });
            
            // 统一新消息给客服人员
            socket.on('customer_push_message',res=>{
                this.newMessage(res.data,res.counts);
            });
            // 统一各个客服去红点操作
            socket.on('customer_readed',res=>{
                this.readed(res.uid,res.counts);
            });
        },
        _setIsTopIndex(){
            let index=0,
                customers=this.customers;
            for(let item of customers){
                if(item.is_top){
                    index++;
                }else{
                    break;
                }
            }
            this.isTopMaxIndex=index;
        },
	    remoteMethod(query) {
	        if (query !== '') {
	        	query=query.toLowerCase()
	          	this.loading = true;
	            this.options4 = this.customers.filter(item => {
	              	return item.name.toLowerCase().indexOf(query) > -1||item.tel.toLowerCase().indexOf(query) > -1;
	            });
	            this.loading = false;
	        } else {
	          this.options4 = [];
	        }
	    },
	    searchChange(show){
            if(!show){
                let uid=this.value9;
                if(!uid||this.row.id==uid){
                    return;
                }
                let index=this.getRowIndex(uid);
                if(index>-1){
                    this.createSession(this.customers[index]);
                }
                
            }
	    },
        /**
         * 打开聊天信息框
         * @param  {[type]} row [description]
         * @return {[type]}     [description]
         */
	    createSession(row){
            if(this.row.id==row.id){
                return;
            }
	    	this.row=row;
	    	this.pull(row.id,row.notReads);
	    	this.close(true);
	    },
	    // 关闭素材选择框
        close(val=false){
            this.value=val;
        },
        /**
         * 发送信息
         * @return {[type]} [description]
         */
        send(){
        	let message=this.trim(this.sessionMessage.toString()),
        		uid=this.row.id;
        	if(!message.length){
        		this.$message({type:'warning',message:'发送的消息不能为空'});
        		return;
        	}
        	this.sessionMessage='';
        	this._wspost("{:url('customer/push')}",{relation_id:uid,message},res=>{
        		if(res.data){
        			this.logs.push(res.data);
        			this.scrollDown();
        			this.changeRow(uid,res.data);
        		}else{
        			this.sessionMessage=message;
        		}
        	},false);
        },
        /**
         * 接收到未读消息已经查看的消息（多客服同步去红点操作）
         * @param  {[type]} uid [description]
         * @return {[type]}     [description]
         */
        readed(uid,counts=0){
            let index=this.getRowIndex(uid);
            if(index>=0){
                let customer=this.customers[index];
                //if(customer.notReads>0){
                    customer.notReads+=counts;
                    this.counts+=counts;
                    this.customers.splice(index,1,customer);
                //}
                
            }
        },
        /**
         * 接收到新消息
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        newMessage(data,counts=0){
            let uid=data.uid;
            if(data.relation_id>0){
                uid=data.relation_id;
            }
            // 正在与该客户通话中
            if(this.value&&this.row.id==uid){ 
                this.logs.push(data);
                this.pull(uid);
            }
            this.changeRow(uid,data,counts);
        },

        /**
         * 会员列表最新消息发生变化
         * @param  {[type]} uid [description]
         * @param  {[type]} row [description]
         * @param  {[type]} notReads 0 设为0 大于0 做累加
         * @return {[type]}     [description]
         */
        changeRow(uid,row,notReads=0){
            let index=this.getRowIndex(uid);
            if(index>=0){
        		let isTopMaxIndex=this.isTopMaxIndex,
                    customer=this.customers[index];
        		customer.message=row.message;
                customer.s_time=row.s_time;
                this.counts+=notReads;
                // if(notReads>0){
                     customer.notReads=parseInt(customer.notReads)+parseInt(notReads);
                // }else if(notReads==0){
                //     customer.notReads=notReads;
                // }
        		this.customers.splice(index,1);
                if(!customer.is_top&&isTopMaxIndex>0){ //存在顶置项
                    this.customers.splice(isTopMaxIndex,0,customer);
                }else{
                    this.customers.unshift(customer)
                }
        		
        	}
        },
        /**
         * 通用户ID查找用户所在位置索引
         * @param  {[type]} uid [description]
         * @return {[type]}     [description]
         */
        getRowIndex(uid){
        	let customers=this.customers,
        		index=-1;
        	for(let i in customers){
        		let item=customers[i];
        		if(item.id==uid){
        			index=i;
        			break;
        		}
        	}
        	return index;
        },
        /**
         * 拉取用户聊天记录
         * @param  {[type]} uid [description]
         * @param  {[type]} notReads [description]
         * @return {[type]}     [description]
         */
        pull(uid,notReads=0){
        	this._wspost("{:url('customer/pull')}",{uid},res=>{
        		this.logs=res.data;
        		if(res.data&&res.data.length){
        			this.scrollDown();
                    // 统一由后台同步红点去除
                    // if(notReads>0){
                    //     this.readed(uid);
                    // }
        		}
        	},false);
        },
        // 聊天框 滚动到底部
        scrollDown(){
            this.$nextTick(_=>{
                let div = document.getElementById('scrollDIV');
                if(div){
                    div.scrollTop = div.scrollHeight;
                }
            })
        },
        // 初始化发送类型
        initEnter(){
            let key=this.prefix+'sendKey',
                sendKey=localStorage.getItem(key);
            if(sendKey){
                this.sendKey=sendKey;
            }else{
                localStorage.setItem(key,this.sendKey);
            }
        },
        // 打开发送消息按键选择列表
        sendKeyType(val){
            val=val||!this.sendKeyTypeShow;
            this.sendKeyTypeShow=val;
        },
        // 选中消息发送按键
        changeSendKey(val){
            let key=this.prefix+'sendKey';
            this.sendKey=val;
            localStorage.setItem(key,val);
            this.sendKeyType(false);
        },
        // 回车发送消息
        enter(){
            window.addEventListener('keyup',e=>{
                if(!this.sessionFocus){
                    return ;
                }
                if(this.sendKey==='enter'&&e.keyCode===13&&!e.ctrlKey){
                    this.send();
                }else if(this.sendKey==='cEnter'&&e.ctrlKey&&e.keyCode===13){
                    this.send();
                }
            })
            window.addEventListener('click',e=>{
                if(this.sendKeyTypeShow&&e.target.id!=='sendKeyType'&&e.target.parentElement.id!=='sendKeyType'){
                    this.sendKeyType(false);
                }
                    
            })
        },
	}
});
</script>

<script>
var wsTop=new Vue({
	el:"#ws-top",
	mixins:[wsMixins],
	data:{},
	methods: {
	    showAside(){
	      	let end=wsNav.aside==0?200:0;
	      	this.tween({aside:wsNav.aside},{aside:end},rs=>{
	        	wsNav.aside=rs.aside;
	      	},200);
	    },
	}
});
</script>

{block name="vue"}
<!-- 这里允许在最后插入javaScript代码(仅为方便使用wsNav、wsTop 变量) -->
{/block}